package com.smasher.print.dw;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import dw.bt.BtHelper;
import dw.printer.Printer;

public class ConnectBT implements ConnectDW {

    public static final String TAG = "ConnectBT";

    private Printer printer;

    private BluetoothDevice mBluetoothDevice;

    private boolean isConnect = false;

    private int retryCount = 0;

    public ConnectBT(Context context, Printer printer) {
        this.printer = printer;
    }

    @Override
    public void start(Context context) {
        permissonCheck(context);
    }

    @Override
    public void stop(Context context) {

    }

    @Override
    public void connPrint(Context context) {
        printer.startSearchBtDevice(new BtHelper.BluetoothMsgCallback() {
            @Override
            public void onStartDiscovery() {
                Log.i(TAG, "onStartDiscovery: ");

            }

            @Override
            public void onStopDiscovery() {
                Log.i(TAG, "onStopDiscovery: ");
            }

            @SuppressLint("MissingPermission")
            @Override
            public void onDiscoveryDevice(BluetoothDevice bluetoothDevice) {
                Log.i(TAG, "onDiscoveryDevice: ");
                String name = bluetoothDevice.getName();
                if (name != null) {
                    Log.i(TAG, "onDiscoveryDevice: " + name);
                    if ("58E_6801".equals(name)) {
                        mBluetoothDevice = bluetoothDevice;
                        printer.stopSerachBtDevice();
                        actualConnect(bluetoothDevice);
                    }

                }
            }

            @Override
            public void connectFailed() {
                Log.i(TAG, "connectFailed: ");
                isConnect = false;
                retry();
            }

            @Override
            public void connectSuccess() {
                Log.i(TAG, "connectSuccess: ");
                isConnect = true;
            }

            @Override
            public void disconnectSuccess() {
                Log.i(TAG, "disconnectSuccess: ");
                isConnect = false;


            }
        });


    }

    private void retry() {
        if (retryCount <= 3) {
            actualConnect(mBluetoothDevice);
            retryCount++;
        }
    }

    @Override
    public void disConnPrint(Context context) {
        printer.closeBt();
    }

    @Override
    public boolean isUnConnect(Context context) {
        Log.i(TAG, "isUnConnect: " + isConnect);
        return !isConnect;
    }


    private void permissonCheck(Context context) {
        List<String> permissions = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12 及以上需要 BLUETOOTH_SCAN 和 BLUETOOTH_CONNECT
            permissions.add(Permission.BLUETOOTH_SCAN);
            permissions.add(Permission.BLUETOOTH_CONNECT);
        } else {
            // Android 11 及以下需要 ACCESS_FINE_LOCATION
            permissions.add(Permission.ACCESS_FINE_LOCATION);
        }

        XXPermissions.with(context)
                .permission(permissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Log.d(TAG, "部分权限未授予");
                            return;
                        }
                        Log.d(TAG, "所有权限已授予");
                        // 开始蓝牙操作
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Log.d(TAG, "权限被永久拒绝");
                            XXPermissions.startPermissionActivity(context, permissions);
                        } else {
                            Log.d(TAG, "权限被拒绝");
                        }
                    }
                });
    }


    private void actualConnect(BluetoothDevice bluetoothDevice) {
        try {
            Method method = BluetoothDevice.class.getMethod("setPin", byte[].class);
            method.invoke(bluetoothDevice, new Object[]{new byte[]{'0', '0', '0', '0'}});
        } catch (Exception e) {
            e.printStackTrace();
        }
        printer.openBt(bluetoothDevice);
    }
}
